<template>
	<view class="myInvite">
		<u-navbar back-text="邀请好友" :border-bottom="false" :background="{
				background: 'rgba(248, 248, 249, 0.86)'
			}"></u-navbar>
		<view class="topheader">
			<view class="tips">可以复制邀请码给好友进入小程序注册时填写</view>
			<view class="tips">直接分享海报包含邀请码信息可直接邀请</view>
			<view class="inviteCode u-flex u-row-around u-col-center">
				<view class="code">{{ my_code }}</view>
				<view class="copy" @click="docopy">复制邀请码</view>
			</view>
		</view>
		<view class="swiperbox">
			<u-swiper :list="list" name="url" :effect3d="true" :height="1022" :autoplay="false" effect3d-previous-margin="54"
			 @change="swiperchange"></u-swiper>
		</view>
		<view class="btns">
			<view class="top btn"><button type="default" class="top btn u-font-24" style="margin-top: 28rpx;" open-type="share">分享小程序</button></view>
			<view class="bot btn">
				<view class="u-font-24" style="margin-top: 24rpx;" @click="getCreateQrCode">分享邀请海报</view>
			</view>
		</view>
		<canvas canvas-id="myCanvas" :style="{ width: 1148 * scale + 'rpx', height: 2044 * scale + 'rpx', backgroundColor: '#FFFFFF' }"
		 class="canvas-hide"></canvas>
	</view>
</template>

<script>
	import uniCopy from '@/js_sdk/xb-copy/uni-copy.js';
	export default {
		name: 'myInvite',
		data() {
			return {
				scale: 1,
				current: 0,
				canvasimg: '',
				my_code: uni.getStorageSync('jxuser') ? uni.getStorageSync('jxuser').my_code : '请先登录',
				list: [
					// {
					// 	url: 'http://img.letuilm.com/2021/01/3e478d2021012017281959132.png',
					// 	qrcode_x: '285',
					// 	qrcode_y: '850'
					// }
				],
				qrcode: ''
			};
		},
		//实例创建完成后被立即调用
		created() {},
		onLoad(option) {
			this.getSharePoster();
		},
		//挂载开始之前被调用
		beforeMount() {},
		onPullDownRefresh() {
			//监听下拉刷新动作的执行方法，每次手动下拉刷新都会执行一次
			console.log('refresh');
			setTimeout(function() {
				uni.stopPullDownRefresh(); //停止下拉刷新动画
			}, 1000);
		},
		//初次渲染完成
		onReady() {},

		//全局只触发一次
		onLaunch() {},
		//从后台进入前台
		onShow() {},
		//前台进入后台
		onHide() {},
		onShareAppMessage(e) {
			return {
				title: '京东购物省钱，分享还能赚钱！',
				path: '/pages/my/index?scene=' + encodeURIComponent(this.skuId + '&' + this.my_code),
				imageUrl: this.canvasimg
			};
		},
		//分享到朋友圈
		onShareTimeline(res) {
			return {
				title: '京东购物省钱，分享还能赚钱！',
				query: {
					scene: encodeURIComponent(this.skuId + '&' + this.my_code)
				},
				imageUrl: '/static/imgs/share_img.png'
			};
		},
		methods: {
			getSharePoster() {
				this.$u.api
					.getSharePoster()
					.then(res => {
						console.log(res);
						this.list = res.data;
						this.getCreateQrCode(1);
					})
					.catch(err => {
						console.log(err);
					});
			},
			docopy() {
				uniCopy({
					content: this.my_code,
					success: res => {
						uni.showToast({
							title: res,
							icon: 'none'
						});
					},
					error: e => {
						uni.showToast({
							title: e,
							icon: 'none',
							duration: 3000
						});
					}
				});
			},
			getCreateQrCode(num) {
				this.$u.api
					.getCreateQrCode({
						path: 'pages/home/index',
						sku_id: '10022101680039',
						code: this.my_code
					})
					.then(res => {
						console.log('小程序码', res);
						this.qrcode = res.data.code;
						setTimeout(() => {
							if (num === 1) {
								this.makeimg(true);
							} else {
								this.makeimg(false);
							}
						}, 300);
					})
					.catch(err => {
						conosle.log(err);
					});
			},
			makeimg(isshare) {
				let _this = this;
				// let phoneWith = this.phoneWith;
				// let scale = (phoneWith * 0.9) / 940;
				let scale = this.scale;
				// console.log(scale);

				uni.showLoading({
					mask: true,
					title: '生成中...'
				});
				// let oneurl = this.oneurl;
				// let base64 = this.base64;
				// console.log(this.list[this.current]);
				let item = this.list[this.current];
				_this.downloadImages(item.url, function(res) {
					// console.log(res);
					console.log('item', item);
					// item.qrcode_x = '285';
					// item.qrcode_y = '850';
					let bgimg = res;

					_this.drawPost(
						'myCanvas',
						574 * scale,
						1022 * scale,
						[{
								type: 'image',
								url: bgimg,
								x: 0,
								y: 0,
								width: 574 * scale,
								height: 1022 * scale,
								isCircle: false
							},
							{
								type: 'image',
								url: _this.qrcode,
								x: (parseInt(item.qrcode_x) - 69) * scale,
								y: (parseInt(item.qrcode_y) - 69) * scale,
								width: 138 * scale,
								height: 138 * scale,
								isCircle: true
							}
						],
						data => {
							console.log('---1', data);
							if (!isshare) {
								_this.preview();
							}
						}
					);
				});
			},
			// canvas绘画封装
			drawPost: function(id, width, height, options, callback) {
				const ctx = uni.createCanvasContext(id);
				// ctx.setFillStyle('#FFFFFF');
				// ctx.fillStyle = '#FFFFFF';
				let that = this;
				// console.log('ctx', ctx);
				for (let i = 0; i < options.length; i++) {
					let setting = options[i];
					if (setting.type == 'image') {
						if (setting.isCircle) {
							let x = setting.x + setting.width / 2;
							let y = setting.y + setting.height / 2;
							let r = setting.height / 2;
							ctx.save();
							ctx.beginPath();
							ctx.arc(x, y, r, 0, 2 * Math.PI);
							ctx.clip();
							ctx.drawImage(setting.url, setting.x, setting.y, setting.width, setting.height);
							ctx.restore();
						} else {
							ctx.drawImage(setting.url, setting.x, setting.y, setting.width, setting.height);
						}
					} else if (setting.type == 'text') {
						let text = setting.text;
						ctx.setFontSize(setting.size);
						ctx.setFillStyle(setting.color);
						if (text.length > 22 && text.length <= 44) {
							let s_text = text.slice(0, 22);
							let e_text = text.slice(22, 44);
							ctx.fillText(s_text, setting.x, setting.y);
							ctx.fillText(e_text, setting.x, setting.y + 18 * this.scale);
							if (setting.bold) {
								for (let i = 0; i < 2; i++) {
									ctx.fillText(s_text, setting.x, setting.y);
									ctx.fillText(e_text, setting.x, setting.y + 18 * this.scale);
								}
							}
						} else if (text.length >= 45) {
							let s_text = text.slice(0, 22);
							let t_text = text.slice(22, 44);
							let e_text = text.slice(44, 67);
							ctx.fillText(s_text, setting.x, setting.y);
							ctx.fillText(t_text, setting.x, setting.y + 18 * this.scale);
							ctx.fillText(e_text, setting.x, setting.y + 38 * this.scale);
							if (setting.bold) {
								for (let i = 0; i < 2; i++) {
									ctx.fillText(s_text, setting.x, setting.y);
									ctx.fillText(t_text, setting.x, setting.y + 18 * this.scale);
									ctx.fillText(e_text, setting.x, setting.y + 38 * this.scale);
								}
							}
						} else if (text.length >= 67) {
							let s_text = text.slice(0, 22);
							let t_text = text.slice(22, 44);
							let e_text = text.slice(44, 63) + '...';
							ctx.fillText(s_text, setting.x, setting.y);
							ctx.fillText(t_text, setting.x, setting.y + 18 * this.scale);
							ctx.fillText(e_text, setting.x, setting.y + 38 * this.scale);
							if (setting.bold) {
								for (let i = 0; i < 2; i++) {
									ctx.fillText(s_text, setting.x, setting.y);
									ctx.fillText(t_text, setting.x, setting.y + 18 * this.scale);
									ctx.fillText(e_text, setting.x, setting.y + 38 * this.scale);
								}
							}
						} else {
							ctx.fillText(setting.text, setting.x, setting.y);
							if (setting.bold) {
								for (let i = 0; i < 2; i++) {
									ctx.fillText(setting.text, setting.x, setting.y);
								}
							}
						}
					} else if (setting.type == 'line') {
						ctx.setFillStyle(setting.color);
						ctx.setStrokeStyle(setting.color);
						ctx.moveTo(setting.x, setting.y);
						ctx.lineTo(setting.x + setting.width, setting.y);
						ctx.stroke();
					}
				}
				ctx.draw(true, function(e) {
					// console.log('e', e);
					uni.hideLoading();
					setTimeout(() => {
						uni.canvasToTempFilePath({
							x: 0,
							y: 0,
							width: 574 * that.scale,
							height: 1022 * that.scale,
							fileType: 'jpg',
							quality: 1, //质量 (0,1]
							canvasId: 'myCanvas',
							success: function(res) {
								// 在H5平台下，tempFilePath 为 base64
								console.log('海报生成成功!', res.tempFilePath);
								that.canvasimg = res.tempFilePath;
								callback(res.tempFilePath);
							},
							fail: function(res) {
								console.log('fail', res);
								uni.hideLoading();
								uni.showToast({
									title: '海报生成失败',
									icon: 'none'
								});
							}
						});
					}, 200);
				});
			},
			// 缓存本地
			downloadImages: function(url, callback) {
				console.log('downloadImagesurl', url);
				uni.downloadFile({
					url: url,
					success: res => {
						console.log('downloadFile', res);
						if (res.statusCode === 200) {
							callback(res.tempFilePath);
						}
					},
					fail: res => {
						uni.hideLoading();
						app.errornet('生成失败');
					}
				});
			},
			preview(index, i) {
				let that = this;
				let arr = [];
				arr.push(this.canvasimg);
				console.log(arr);
				uni.previewImage({
					urls: arr,
					current: arr[0]
				});
			},
			dosave(url) {
				let that = this;
				// #ifdef  MP
				console.log('-----', url);
				uni.getSetting({
					success(res) {
						uni.downloadFile({
							url: url,
							success: res => {
								if (res.statusCode === 200) {
									console.log('MP', res.tempFilePath);
									uni.saveImageToPhotosAlbum({
										filePath: res.tempFilePath,
										success: res => {
											that.$refs.uToast.show({
												title: '保存成功',
												type: 'success'
											});
										},
										fail: err => {
											that.$refs.uToast.show({
												title: '保存失败',
												type: 'error'
											});
										}
									});
								}
							},
							fail: res => {
								that.$refs.uToast.show({
									title: '下载失败',
									type: 'error'
								});
							}
						});
					}
				});
				// #endif

				// #ifdef APP-PLUS
				uni.getImageInfo({
					src: url,
					success(image) {
						console.log('----app', image.path);
						uni.saveImageToPhotosAlbum({
							filePath: image.path,
							success: () => {
								// that.$refs.uToast.show({
								// 	title: '保存成功',
								// 	type: 'success'
								// });
							}
						});
					}
				});
				// #endif

				// #ifdef H5
				var canvas = document.createElement('canvas');
				var img = document.createElement('img');
				img.onload = function(e) {
					canvas.width = img.width;
					canvas.height = img.height;
					var context = canvas.getContext('2d');
					context.drawImage(img, 0, 0, img.width, img.height);
					canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
					canvas.toBlob(blob => {
						let link = document.createElement('a');
						link.href = window.URL.createObjectURL(blob);
						link.download = '';
						link.click();
					}, 'image/jpeg');
				};
				img.setAttribute('crossOrigin', 'Anonymous');
				img.src = url;

				// this.$refs.uToast.show({
				// 	title: '保存成功',
				// 	type: 'success'
				// });
				// #endif
			},
			swiperchange(index) {
				console.log(index);
				this.current = index;
			}
		}
	};
</script>

<style lang="scss" scoped>
	.myInvite {
		background-color: rgba(248, 248, 249, 0.86);

		.topheader {
			text-align: center;

			.tips {
				color: #919191;
				font-size: 24rpx;
				text-align: center;
				padding-bottom: 20rpx;
			}

			.inviteCode {
				.code {
					background-color: #ffc8af;
					width: 400rpx;
					height: 96rpx;
					line-height: 96rpx;
					text-align: center;
					color: #873800;
					border-radius: 12rpx;
					font-size: 72rpx;
				}

				.copy {
					color: #cf1322;
					font-size: 40rpx;
				}
			}
		}

		.swiperbox {
			margin-top: 48rpx;
		}

		.btns {
			width: 590rpx;
			margin: 0 auto;
			text-align: center;
			padding-bottom: 0;
			padding-bottom: constant(safe-area-inset-bottom);
			padding-bottom: env(safe-area-inset-bottom);

			.btn {
				width: 590rpx;
				height: 70rpx;
				line-height: 70rpx;
				border-radius: 100rpx;
				color: #ffffff;
				text-align: center;
			}

			.top {
				background-color: #fdaf8e;
				color: #621e00;
			}

			.bot {
				background-color: #f95d4e;
			}
		}

		.canvas-hide {
			/* 1 */
			position: fixed;
			right: 100vw;
			bottom: 100vh;
			/* 2 */
			z-index: -9999;
			/* 3 */
			opacity: 0;
		}
	}
</style>
